﻿
CREATE FUNCTION [dbo].[APR] (
	@Tier varchar(50),
	@ModelAge int,
	@Term int,
	@NDay int,
	@Used bit,
	@State char(2),
	@Franchise int,
	@DateStarted smalldatetime = '3/2/2005 1:00'
) RETURNS numeric(10,2)
BEGIN 
DECLARE @ret numeric(10,2)

IF @Used = 0 SET @ModelAge =  -1
	
IF @Tier IN ('D1','E','G','GG','NewStart') SET @Tier = 'D'

SET @Term = ROUND(@Term/6.0,0)*6

IF @State = 'FL' BEGIN
	IF @Tier LIKE 'BK%' SET @Tier = SUBSTRING(@Tier,4,1)
	SELECT @ret = APR FROM v_APR1
	WHERE	Tier=@Tier AND
			ModelAge = @ModelAge AND
			Term = @Term AND
			NDay = @NDay AND
			State = @State
END
ELSE BEGIN
	SELECT TOP 1 @Ret = APR FROM  t_APR_IL
	WHERE 
				((@Tier LIKE 'BK%' AND Tier = @Tier) OR (NOT @Tier LIKE 'BK%' AND SUBSTRING(@Tier,1,1) = Tier))
					AND
				ModelAge = @ModelAge AND
				State = @State AND
				@DateStarted > DateStart
				--AND	Franchise = @Franchise
	ORDER BY DateStart DESC
END
RETURN @ret
END




